package com.tom.demo.common.config;

import com.tom.demo.common.constant.CacheConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.List;

/**
 * Knife4j接口访问文档
 * <a href="http://127.0.0.1:8089/component/management/back/api/doc.html">...</a>  （Knife4j访问地址）
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        // 创建一个Parameter对象表示全局的请求头参数
        ParameterBuilder authorizationHeader = new ParameterBuilder();
        authorizationHeader
                .name(header) // 请求头 Authorization
                .defaultValue(CacheConstants.GLOBAL_LOGIN_TOKEN_KEY)//默认值
                .description("访问令牌") // 参数描述
                .modelRef(new ModelRef("string")) // 参数类型
                .parameterType("header") // 参数类型：header, query等
                .required(true) // 是否必填
                .build();
        List<Parameter> globalHeaders = Lists.newArrayList(authorizationHeader.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true)
                .apiInfo(apiInfo())
                .groupName("2.X版本")
                .select()
                //这里只扫描那些带@Api注解的controller
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //所有接口地址都显示
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(globalHeaders); // 添加全局请求头参数
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("LQ系统-API文档")
                .description("本文档描述了系统在开发中定义的所有接口")
                .version("1.0")
                .description("项目接口文档")
                .contact(new Contact("兰强", "https://www.baidu.com", "1176209214@qq.com"))
                .build();
    }
}
